﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI;
using NPOI.HSSF.UserModel;
using System.Data;
using NPOI.SS.UserModel;
using System.IO;

namespace Infrastructure
{
    public class ExcelHelp
    {

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="Title"></param>
        public static void ExportExcel(DataTable dt, string Title)
        {
            MemoryStream ms = new MemoryStream();
            HSSFWorkbook workBook = new HSSFWorkbook();
            int rowCount = 0;
            var sheet1 = workBook.CreateSheet("Sheet1");
            var row = sheet1.CreateRow(rowCount);
            rowCount++;
            row.CreateCell(0).SetCellValue(Title);
            foreach (DataRow dr in dt.Rows)
            {
                row = sheet1.CreateRow(rowCount);

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    row.CreateCell(i).SetCellValue(dr[i].ToString());
                }
                rowCount++;
            }
            using (FileStream fs = new FileStream(Title, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();

                fs.Write(data, 0, data.Length);
                fs.Flush();

                data = null;
            }
        }
    }
}
